import { call, put, fork, select, take } from 'redux-saga/effects'
import { message } from 'antd'
import actions,{ GET_DATA, DELETE_SIGN, SET_DEFAULT } from '@/actions/sign'
import api from '@/api/sign'
import util from '@/utils'
import successDesc from '@/constants/success'

function* getData() {
  try {
    const params = yield select(({ signReducer }) => util.pick(signReducer, [
      'pageNum', 
      'pageSize', 
      'sign', 
      'status', 
      'startTime', 
      'endTime',
    ]))
    const { startTime, endTime } = params       
    params.startTime = util.formatDay(startTime)
    params.endTime = util.formatDay(endTime)
    const { isSuccess, data, desc } = yield call(api.getSignData, params)
    if(isSuccess && data && Array.isArray(data.list)){
      yield put(actions.getDataSuccess(data))
      //!data.size && message.warning(desc)
    }else {
      throw new Error(desc)
    }
  } catch (error) {
    yield put(actions.getDataFail())
    message.error(error.message || '获取数据错误')
  }
}

function* deleteSign(data) {
  try {
    const { isSuccess, desc} = yield call(api.deleteSign, data)
    if(isSuccess) {
      yield put(actions.deleteSignSuccess())
      yield put(actions.getData())
      message.success(successDesc.delete)
    }else {
      throw new Error(desc)
    }
  } catch (error) {
    yield put(actions.deleteSignFail())
    message.error(error.message || '删除签名错误')
  }
}

function* setDefault(params) {
  try {
    const { isSuccess, desc } = yield call(api.setDefault, params)
    if(isSuccess){
      yield put(actions.setDefaultSuccess())
      yield put(actions.getData())
      message.success(successDesc.setDefault)
    }else {
      throw new Error(desc)
    }
  } catch (error) {
    yield put(actions.setDefaultFail())
    message.error(error.message || '设置默认错误')
  }
}

function* watchSetDefault() {
  while (true) {
    const { data: { id } } = yield take(SET_DEFAULT)
    yield call(setDefault, { id })
  }
}

function* watchDeleteSign(){
  while (true) {
    const { data: { id, status }} = yield take(DELETE_SIGN)
    yield call(deleteSign, { id, status})
  }
}

function* watchGetData() {
  while (true) {
    yield take(GET_DATA)
    yield call(getData)
  }
}

export default [
  fork(watchGetData),
  fork(watchDeleteSign),
  fork(watchSetDefault),
]